package io.github.iogogogo.commons.util;

import com.google.common.io.ByteStreams;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.file.Paths;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * Created by tao.zeng on 2024/11/7.
 */
@Slf4j
public class ResourceUtils {

    private static String defaultConf(String confName) {
        Optional<InputStream> optional = Optional.ofNullable(ResourceUtils.class.getResourceAsStream(confName));
        return optional.map(x -> {
            try {
                return new String(ByteStreams.toByteArray(x));
            } catch (IOException e) {
                log.error("load config failure", e);
            }
            return null;
        }).orElseThrow(() -> new NullPointerException("Configuration cannot be empty."));
    }

    public static String defaultConf(String confName, String... args) {
        InputStream inputStream = null;
        try {
            if (args.length == 0) {
                inputStream = ResourceUtils.class.getClassLoader().getResourceAsStream(confName);
            } else {
                inputStream = new FileInputStream(Paths.get(args[0]).toFile());
            }

            if (Objects.isNull(inputStream)) throw new NullPointerException("Configuration cannot be empty.");

            return new BufferedReader(new InputStreamReader(inputStream))
                    .lines().collect(Collectors.joining(System.lineSeparator()));
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } finally {
            IoUtils.close(inputStream);
        }
    }
}
